package com.panshi.generate;

        import java.io.File;
        import java.io.UnsupportedEncodingException;
        import java.net.URLDecoder;
        import java.sql.Connection;
        import java.sql.DriverManager;
        import java.sql.SQLException;

        import com.jfinal.plugin.IPlugin;

public class AutoModelPlugin implements IPlugin {
    private Connection conn = null;
    private String basePath = "";
    private String packageName = "";
    private String baseModelClass = "";
    private String connectUrl = "";
    private String userName = "";
    private String userPassword = "";
    private String driverClass = "com.mysql.jdbc.Driver";
    private String modelSavapath ="";
    public static String templatePath = "";
    public AutoModelPlugin(String connectUrl, String userName,
                           String userPassword, String packageName, String baseModelClass,String modelSavapath) {
        this.connectUrl = connectUrl;
        this.userName = userName;
        this.userPassword = userPassword;
        this.packageName = packageName;
        this.baseModelClass=baseModelClass;
        this.modelSavapath = modelSavapath;
        templatePath = modelSavapath;
        getConnection();
    }

    public AutoModelPlugin(String driverClass, String connectUrl,
                           String userName, String userPassword, String packageName,
                           String baseModelClass,String modelSavapath) {
        this.connectUrl = connectUrl;
        this.userName = userName;
        this.userPassword = userPassword;
        this.packageName = packageName;
        this.driverClass = driverClass;
        this.baseModelClass=baseModelClass;
        this.modelSavapath = modelSavapath;
        getConnection();
    }


    private void getConnection() {
        try {
            Class.forName(this.driverClass);
            this.conn = DriverManager.getConnection(connectUrl, userName, userPassword);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public boolean start() {
        Class objClass = this.getClass();
        String strRealPath  = objClass.getClassLoader().getResource("").getFile();
        try {
            strRealPath = URLDecoder.decode(strRealPath, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        File objFile = new File(strRealPath);
        basePath = objFile.getParent();
        String modelSavapath= this.modelSavapath;;
        JavaSourceFactory.generateModels(conn, basePath, packageName,baseModelClass,modelSavapath);
        return true;
    }

    public boolean stop() {
        return true;
    }

    public String getModelSavapath() {
        return modelSavapath;
    }

    public void setModelSavapath(String modelSavapath) {
        this.modelSavapath = modelSavapath;
    }
}